
#include "netser.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

netser::netser(std::string outip, int outport)
{
    this->outip = outip;
    this->outport = outport;

    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        std::cerr << "Could not create socket" << std::endl;
        return;
    }
}

netser::~netser()
{
    close(fd);
}

int netser::send(char* buf, size_t len, struct sockaddr_in* outaddr)
{
    int ret = 0;

    ret = sendto(fd, (const char*)buf, len, MSG_CONFIRM, (struct sockaddr*)outaddr, sizeof(struct sockaddr_in));
    if (ret < 0) {
        std::cerr << "Send failed, ret = " << ret << std::endl;
        return -1;
    }

    return 0;
}

int netser::start()
{
    if (!handle.joinable()) {
        running = true;
        handle = std::thread(&netser::thread, this);
    }

    return 0;
}

int netser::stop()
{
    if (handle.joinable()) {
        running = false;
        handle.join();
    }

    return 0;
}

void netser::thread()
{
    char buf[32] = "hello aiit";
    struct sockaddr_in outaddr;

    /* 构造目标地址结构体 */
    memset(&outaddr, 0, sizeof(outaddr));
    outaddr.sin_family = AF_INET;
    outaddr.sin_port = htons(outport);
    inet_pton(AF_INET, outip.data(), &outaddr.sin_addr);

    while (running) {
        send(buf, strlen(buf), &outaddr);
        usleep(40 * 1000);
    }
}
